﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HallTimer.Interfaces;
using System.Windows.Controls;
using System.ComponentModel;
using System.Windows.Threading;

namespace HallTimer.Classes
{
    public class CountDownTimer
    {
        public const int TIMER_INTERVAL = 1000; // in milliseconds
        public const int TIMESPAN_MILLISECONDS_SIZE = 7; // it always has seven digits

        private DispatcherTimer backgroundTimer;
        private ITimerCallback callback;

        public TimeSpan TotalTime { get; set; }
        public DateTime StartedTime { get; set; }

        public CountDownTimer(ITimerCallback callbackPage,  int totalMinutes)
        {
            TotalTime = new TimeSpan(0, totalMinutes, 0);
            backgroundTimer = new DispatcherTimer();
            backgroundTimer.Interval = TimeSpan.FromMilliseconds(TIMER_INTERVAL);
            backgroundTimer.Tick += new EventHandler(timer_Elapsed); // when interval ends (each second - see constant TIMER_INTERVAL)
            this.callback = callbackPage;
            backgroundTimer.Start();
            StartedTime = DateTime.Now;
            //backgroundTimer.SynchronizingObject = (ISynchronizeInvoke)callbackPage;
        }

        private void timer_Elapsed(object sender, EventArgs e)
        {
            //callback.showTimerValue(DateTime.Now - DateTime.MinValue);
            TimeSpan currentTotal = DateTime.Now - StartedTime;
            TimeSpan timeLeft = TotalTime - currentTotal;
            
            callback.showTimerValue(roundTimespan(timeLeft));
        }

        public void StopTimer()
        {
            backgroundTimer.Stop();
        }

        private TimeSpan roundTimespan(TimeSpan timeSpan) 
        {
            int precision = 0; // don't need the milliseconds
            // convert the digitsToShow into a rounding/truncating mask
            int factor = (int)Math.Pow(10, (TIMESPAN_MILLISECONDS_SIZE - precision));
            return new TimeSpan(((long)Math.Round(((double)timeSpan.Ticks / factor)) * factor));
        }


    }
}
